package com.hxd.tabactivityfragment.ui.fragment


import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.support.v7.widget.GridLayoutManager
import android.view.View
import com.hjq.permissions.OnPermission
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hxd.tabactivityfragment.R
import com.hxd.tabactivityfragment.adapter.HomeImpAdapter
import com.hxd.tabactivityfragment.common.MyFragment
import com.hxd.tabactivityfragment.bean.IMPItem
import com.hxd.tabactivityfragment.mvp.presenter.HomePresenter
import com.hxd.tabactivityfragment.mvp.view.IHomeView
import com.hxd.tabactivityfragment.ui.activity.DataExhibitionActivity
import com.hxd.tabactivityfragment.ui.activity.WebActivity
import com.hxd.tabactivityfragment.util.GsonToBean
import com.hxd.tabactivityfragment.util.L
import com.hxd.tabactivityfragment.util.ThreadUtil
import com.hxd.tabactivityfragment.util.URLProviderUtils
import com.kymjs.rxvolley.RxVolley
import com.kymjs.rxvolley.client.HttpCallback
import com.kymjs.rxvolley.client.HttpParams
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.xuexiang.xui.widget.banner.widget.banner.BannerItem
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.bean.ZxingConfig
import com.yzq.zxinglibrary.common.Constant
import kotlinx.android.synthetic.main.fragment_home.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.support.v4.startActivity


/**
 *  项目名：    Tab+Activity+Fragment
 *  包名：      com.hxd.tabactivityfragment.ui.fragment
 *  文件名:     HomeFragment
 *  创建者:     HXD
 *  创建时间:   2019/3/7 15:51
 *  描述:       主页的Fragment
 */

class HomeFragment : MyFragment(), IHomeView{

    //设置单例静态方法
    companion object {
        fun newInstance(): HomeFragment {
            return HomeFragment()
        }
    }

    private var impDatas: ArrayList<IMPItem.Row> = ArrayList()
    private var adapter: HomeImpAdapter? = null
    private var mHomePresenter: HomePresenter? = null
    private var size: Int = 8
    private val REQUEST_CODE_SCAN:Int = 1111



    override fun getTitleBarId(): Int {
        return R.id.tb_home_title
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_home
    }

    //使用refreshLayout
    override fun getRefreshLayout(): SmartRefreshLayout? {
        return refreshLayout
    }

    override fun initData() {
        mHomePresenter = HomePresenter(getFragmentActivity()!!)
        mHomePresenter!!.bindView(this)
        mHomePresenter!!.initItemData()
        mHomePresenter!!.initBeannerData(sib_home_banner)
        adapter = HomeImpAdapter(impDatas, getFragmentActivity()!!.applicationContext)
    }

    override fun initView() {
        super.initView()
        recyclerView_1.adapter = adapter
        val layoutManager1 = GridLayoutManager(context, 2)
        recyclerView_1.layoutManager = layoutManager1
    }

    override fun initListener() {
        refreshLayout.setOnRefreshListener {
            it.finishRefresh(1000).let {
                adapter!!.setRandData()
                myToast("刷新成功")
            }
        }

        refreshLayout.setOnLoadMoreListener {
            it.finishLoadMore(2000).let {
                myToast("加载更多成功")
                mHomePresenter!!.loadItemData(size)
                //是size没次4的增量
                size += 4
            }
        }

        adapter?.setOnItemClickLitener(object : HomeImpAdapter.OnItemClickLitener {
            override fun onItemClick(view: View, position: Int, proUrl: String) {
                L.i("商品链接是 $proUrl")
                var intent = Intent(activity, WebActivity::class.java)
                intent.putExtra("url", proUrl)
                startActivity(intent)
                L.i("商品链接是 $proUrl")
            }
        })

        tb_home_title.rightView.onClick {
            XXPermissions.with(getFragmentActivity()).permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE).request(object :
                OnPermission {
                //权限获取成功
                override fun hasPermission(granted: List<String>, isAll: Boolean) {
                    val intent = Intent(getFragmentActivity(), CaptureActivity::class.java)
                    val config = ZxingConfig()
                    config.isFullScreenScan = false//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                    intent.putExtra(Constant.INTENT_ZXING_CONFIG, config)
                    startActivityForResult(intent, REQUEST_CODE_SCAN)
                }
                //权限获取失败
                override fun noPermission(denied: List<String>, quick: Boolean) {
                    myToast("没有权限无法扫描呦")
                }
            })
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                val content = data.getStringExtra(Constant.CODED_CONTENT)
                var params = HttpParams()
                params.putJsonParams(GsonToBean.QueryToJson(content))
                RxVolley.jsonPost(URLProviderUtils.getIMPSearchUrl(),params, object : HttpCallback() {
                    override fun onSuccess(result: String?) {
                        L.i("FindFragment_success : $result")
                        rxDialogShapeLoading!!.show()
                        Handler().postDelayed({
                            rxDialogShapeLoading!!.dismiss()
                            startActivity<DataExhibitionActivity>("result" to result!!)
                        }, 1500)
                    }

                    override fun onFailure(errorNo: Int, strMsg: String?) {
                        ThreadUtil.runOnMainThread(Runnable {
                            L.i("FindFragment : $strMsg")
                            myToast("$strMsg")
                        })
                    }
                })
            }
        }
    }

    override fun setLoadingText(): String? {
        return "正在加载中......"
    }

    override fun getBannerDataSuccess(bannerData: ArrayList<BannerItem>) {

    }

    override fun getItemDataSuccess(rows: ArrayList<IMPItem.Row>) {
        adapter!!.setNotifyDataSetChanged(rows)
    }

    override fun getPermissionSuccess() {

    }

    override fun getPermissionFail() {

    }

    override fun getDataFail(msg: String) {
        myToast(msg)
    }

    override fun isStatusBarEnabled(): Boolean {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled()
    }

}